package bi.uc.login;

import java.io.File;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.bi_uc.www.R;

import bi.uc.client.ExitApplication;
import bi.uc.client.MainActivity;
import bi.uc.client.SocketService;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.*;

public class LoginActivity extends Activity implements OnClickListener,
		Runnable {

	public EditText mUserName;
	public EditText mPassword;
	public Button mLoginButton;
	public ImageButton mDropDown;
	public DBHelper dbHelper;
	public CheckBox mCheckBox;
	public PopupWindow popView;
	public MyAdapter dropDownAdapter;
	private ProgressDialog pd;
	private Handler handler;
	private int times = 0;
	private Info info = Info.getInfo();
	private ProgressDialog pBar;
	private String packageName;
	/*
	 * private void initStrictMode() { // 判断操作系统是Android版本3.0以上版本 if
	 * (android.os.Build.VERSION.SDK_INT >= 11) { StrictMode.setThreadPolicy(new
	 * StrictMode.ThreadPolicy.Builder()
	 * .detectDiskReads().detectDiskWrites().detectNetwork()
	 * .penaltyLog().build());
	 * 
	 * StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
	 * .detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath() .build()); } }
	 */

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		((ExitApplication)getApplication()).addActivity(this);
		// 输入法自动调整
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
		// Set our view from the "main" layout resource
		setContentView(R.layout.loginactivity);
		// initStrictMode();
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				int what = msg.what;
				switch (what) {
				case 0:
					if (times < 3) {
						new Thread(LoginActivity.this).start();
					} else {
						times = 0;
						pd.dismiss();
						Toast.makeText(LoginActivity.this, (String) msg.obj,
								Toast.LENGTH_SHORT).show();
					}
					break;
				case 1:
					jumpActivity();
					break;

				case 2:
					packageName = LoginActivity.this.getPackageName();

					String nowVersion = getVerCode(LoginActivity.this);

					String newVersion = (String) msg.obj;
					Log.e("new vision", newVersion);
					Log.e("now vision", nowVersion);
					if (newVersion.equals("Error")) {
						return;
					}

					if (Double.valueOf(newVersion) > Double.valueOf(nowVersion)) {
						doNewVersionUpdate(nowVersion, newVersion);
					}

					break;
				case 3:
					ToastUtil toastUtil = new ToastUtil(LoginActivity.this);
					toastUtil.showDefultToast("下载成功！！").show();
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setDataAndType(Uri.fromFile(new File(
							"/sdcard/bi/", "bi.apk")),
							"application/vnd.android.package-archive");
					startActivity(intent);
					pBar.cancel();
					break;
				case 4:
					ToastUtil toastUtil1= new ToastUtil(LoginActivity.this);
					toastUtil1.showDefultToast("下载失败！！").show();

					pBar.cancel();

					break;
				}

			}
		};
		
		initWidget(); // 加载控件
		initLoginUserName(); // 登录
		if (!info.stopFlag) {
			goToCheckNewVersion();
		} 	
	}

	/**
	 * 
	 *//*
	private void checkUpdataApk() {
		// TODO Auto-generated method stub
		packageName = this.getPackageName();
		String nowVersion = getVerCode(LoginActivity.this);
		String newVersion = goToCheckNewVersion();
		Log.e("new vision", newVersion);
		Log.e("now vision", nowVersion);
		if (newVersion.equals("Error")) {
			return;
		}
		Log.e("new vision", newVersion);
//		if (Integer.valueOf(newVersion) > Integer.valueOf(nowVersion)) {
//			doNewVersionUpdate(nowVersion, newVersion);
//		}
		return;

	}*/

	/**
	 * @param nowVersion
	 * @param newVersion
	 */
	protected void doNewVersionUpdate(String nowVersion, String newVersion) {
		// TODO Auto-generated method stub
		StringBuffer sb = new StringBuffer();
		sb.append("当前版本:");
		sb.append(nowVersion);
		sb.append(", 发现新版本:");
		sb.append(newVersion);
		sb.append(", 是否更新?");
		Dialog dialog = new AlertDialog.Builder(this)
				.setTitle("软件更新")
				.setMessage(sb.toString())
				// 设置内容
				.setPositiveButton("更新",// 设置确定按钮
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								pBar = new ProgressDialog(
										LoginActivity.this);
								pBar.setTitle("正在下载");
								pBar.setMessage("请稍候...");
								// pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
								pBar.show();
								goToDownloadApk();
							}
						})
				.setNegativeButton("暂不更新",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								// 点击"取消"按钮之后退出程序
//								finish();
							}
						}).create();// 创建
		// 显示对话框
		dialog.show();

	}

	/**
	 * 
	 */
	protected void goToDownloadApk() {
		// TODO Auto-generated method stub
		new Thread(new DownloadApkThread(handler)).start();  
	}

	/**
	 * @return
	 */
	private void goToCheckNewVersion() {
		// TODO Auto-generated method stub
		System.out.println("goToCheckNewVersion");
		final String url = "http://bi.bi-uc.com/UpgradeFile/Android/ApkVision.txt";
		
		new Thread(new Runnable() {
			public void run() {
				HttpConnect hc = new HttpConnect(url, LoginActivity.this);
				String newVersion = hc.getDataAsString(null);
				Message message = handler.obtainMessage(2, newVersion);
				handler.sendMessage(message);
			}
		}).start();
				
	}

	/**
	 * @param loginActivity
	 * @return
	 */
	private String getVerCode(Context context) {
		// TODO Auto-generated method stub
		int verCode = 0;
		String verName = null;
		try {
			verCode = context.getPackageManager()
					.getPackageInfo(packageName, 0).versionCode;
			verName = context.getPackageManager()
					.getPackageInfo(packageName, 0).versionName;
		} catch (NameNotFoundException e) {
			System.out.println("no");
		}
		System.out.println("verCode" + verCode + "===" + "verName" + verName);
		return verName;
	}

	private void initWidget() {
		info.stopFlag = !isConnect(this);
		dbHelper = new DBHelper(this);
		mUserName = (EditText) findViewById(R.id.username);
		mPassword = (EditText) findViewById(R.id.password);
		mLoginButton = (Button) findViewById(R.id.login);
		mDropDown = (ImageButton) findViewById(R.id.dropdown_button);
		mCheckBox = (CheckBox) findViewById(R.id.remember);
		mLoginButton.setOnClickListener(this);
		mDropDown.setOnClickListener(this); // 下拉按钮
		Log.d("****debug****", "1111111");		
	}

	/**
	 * 
	 */
	protected void jumpActivity() {
		// TODO Auto-generated method stub
		pd.dismiss();
		dbHelper.cleanup();
		dbHelper.close();
		this.startService(new Intent(LoginActivity.this, SocketService.class)); 
		Intent intent = new Intent(LoginActivity.this, MainActivity.class);
		startActivity(intent);
		this.finish();
	}

	private void initLoginUserName() {
		// Log.Debug("****debug****", "22222"); 从数据库加载历史用户名
		String[] usernames = dbHelper.queryAllUserName();
		if (usernames.length > 0) {
			
			String tempName = usernames[usernames.length - 1];
			mUserName.setText(tempName);
			mUserName.setSelection(tempName.length());
			String tempPwd = dbHelper.queryPasswordByName(tempName);
			int checkFlag = dbHelper.queryIsSavedByName(tempName);
			if (checkFlag == 0) {
				mCheckBox.setChecked(false);
			} else if (checkFlag == 1) {
				mCheckBox.setChecked(true);
			}
			mPassword.setText(tempPwd);
		}
		
		mUserName.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				mPassword.setText("");
			}

		});
	}

	private void AccessIsAllowed() throws Exception {
		String Url = "http://bi.bi-uc.com/BI.api";
		String Body = "Action=PDA-账号登录&aOperator_Account="
				+ mUserName.getText() + "&aOperator_Key=" + mPassword.getText();
		byte[] bs = Body.getBytes("UTF-8");
		URL u = new URL(Url);
		HttpURLConnection con = (HttpURLConnection) u.openConnection();
		con.setRequestMethod("POST");
		con.setConnectTimeout(6*1000);
		con.setDoOutput(true);
		con.setDoInput(true);
		con.setUseCaches(false);
		con.setRequestProperty("Content-length", "" + bs.length);
		// httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
		con.setRequestProperty("Charset", "UTF-8");
		con.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		// httpConn.setRequestProperty("Content-Type",
		// "application/octet-stream");
		OutputStream write = con.getOutputStream();
		write.write(bs);
		write.flush();
		write.close();

		
		int responseCode = con.getResponseCode();
		if (HttpURLConnection.HTTP_OK == responseCode) {// 连接成功
			/* StringBuffer sb = new StringBuffer();
			 String readLine;
			 BufferedReader responseReader = new BufferedReader(
			 new InputStreamReader(con.getInputStream(), "UTF-8"));		 									
			  while ((readLine = responseReader.readLine()) != null) {
			  sb.append(readLine).append("\n"); } 
			  responseReader.close();
			  String string = sb.toString();
			  Log.d("data1", string.substring(0, string.length()/4));
			  Log.d("data2", string.substring(string.length()/4, string.length()/2));
			  Log.d("data3", string.substring(string.length()/2, string.length()*3/4));
			  Log.d("data4", string.substring(string.length()*3/4, string.length()));*/

			XmlPullParserFactory pullParserFactory = XmlPullParserFactory
					.newInstance();
			// 获取XmlPullParser的实例
			XmlPullParser parser = pullParserFactory.newPullParser();
			// parser.setInput(new InputStreamReader(con.getInputStream(),
			// "UTF-8"));
			InputStreamReader responseReader = new InputStreamReader(
					con.getInputStream(), "UTF-8");
			parser.setInput(responseReader);
			parser.next();			
			int eventType = parser.getEventType();			
			if (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG
						&& parser.getName().equals("XML")) {
					// String result = parser.getAttributeValue(0);
					String result = parser.getAttributeValue(null, "EXEC");
					if (result.equals("True")) {
						Message message = handler.obtainMessage(1);
						info.saveData(parser, eventType);
						handler.sendMessage(message);												
					} else {
						Message message = handler.obtainMessage(0,
								parser.getAttributeValue(null, "错误消息"));
						handler.sendMessage(message);
						// pd.dismiss();
						// Toast.makeText(this, parser.getAttributeValue(1),
						// Toast.LENGTH_SHORT).show();
					}
				}
			}
			responseReader.close();
			con.disconnect();
			
		} else {
			con.disconnect();
			
			runOnUiThread(new Runnable() {				
				@Override
				public void run() {
					pd.dismiss();
					Toast.makeText(LoginActivity.this, "连接超时，请确保网络连接正常！", Toast.LENGTH_SHORT).show();
					}
			});	
		}
	} // 发送数据到后台验证帐号密码

	/*
	 * userInfo.put("userID", parser.getAttributeValue(null, "标识"));
	 * userInfo.put("employID", parser.getAttributeValue(null, "商家标识"));
	 * userInfo.put("shopID", parser.getAttributeValue(null, "店面标识"));
	 */

	public void initPopView(String[] usernames) {
		List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < usernames.length; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("name", usernames[i]);
			map.put("drawable", R.drawable.xicon);
			list.add(map);
		}
		dropDownAdapter = new MyAdapter(this, list, R.layout.dropdown,
				new String[] { "name", "drawable" }, new int[] { R.id.textview,
						R.id.delete });
		ListView listView = new ListView(this);
		listView.setAdapter(dropDownAdapter);

		popView = new PopupWindow(listView, mUserName.getWidth(),
				ViewGroup.LayoutParams.WRAP_CONTENT, true);
		popView.setFocusable(true);
		popView.setTouchable(true);

		popView.setBackgroundDrawable(getResources().getDrawable(
				android.R.drawable.screen_background_light));

		// popView.showAsDropDown(mUserName);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.login:
			if (info.stopFlag) {
				Toast.makeText(this, "网络未连接，请确保您的网络已连接！", Toast.LENGTH_SHORT)
						.show();
			} else {
				pd = ProgressDialog.show(this, "", "正在验证帐号密码…");
				new Thread(this).start();
			}
			break;
		case R.id.dropdown_button:
			if (popView != null) {
				if (!popView.isShowing()) {
					popView.showAsDropDown(mUserName);
				} else {
					popView.dismiss();
				}
			} else {
				// 如果有已经登录过账号
				if (dbHelper.queryAllUserName().length > 0) {
					initPopView(dbHelper.queryAllUserName());
					if (!popView.isShowing()) {
						popView.showAsDropDown(mUserName);
					} else {
						popView.dismiss();
					}
				} else {
					Toast.makeText(this, "无记录", Toast.LENGTH_SHORT).show();
				}

			}
			break;
		}
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		times++;
		String userName = mUserName.getText().toString();
		String password = mPassword.getText().toString();
		// 如果勾选记住密码，则保存帐号密码
		if (mCheckBox.isChecked()) {
			dbHelper.insertOrUpdate(userName, password, 1);
		} else {
			dbHelper.insertOrUpdate(userName, "", 0); // 只保存帐号
		}
		// Toast.makeText(this, "记录已经保存", Toast.LENGTH_SHORT).show();
		try {
			AccessIsAllowed();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 验证帐号密码是否允许通过
	}

	private boolean isConnect(Context context) {
		ConnectivityManager conManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo networkInfo = conManager.getActiveNetworkInfo();
		if (networkInfo != null) { // 注意，这个判断一定要的哦，要不然会出错
			return networkInfo.isAvailable();
		}
		return false;
	}

	class MyAdapter extends SimpleAdapter {

		private List<HashMap<String, Object>> data;

		public MyAdapter(Context context, List<HashMap<String, Object>> data,
				int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
			this.data = data;
		}

		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public Object getItem(int position) {
			return position;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			System.out.println(position);
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(LoginActivity.this).inflate(
						R.layout.dropdown, null);
				holder.btn = (ImageButton) convertView
						.findViewById(R.id.delete);
				holder.tv = (TextView) convertView.findViewById(R.id.textview);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.tv.setText(data.get(position).get("name").toString());
			holder.tv.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					String[] usernames = dbHelper.queryAllUserName();
					mUserName.setText(usernames[position]);
					mPassword.setText(dbHelper
							.queryPasswordByName(usernames[position]));
					popView.dismiss();
				}
			});
			holder.btn.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					String[] usernames = dbHelper.queryAllUserName();
					if (usernames.length > 0) {
						dbHelper.delete(usernames[position]);
					}
					String[] newusernames = dbHelper.queryAllUserName();
					if (newusernames.length > 0) {
						initPopView(newusernames);
						popView.showAsDropDown(mUserName);
					} else {
						popView.dismiss();
						popView = null;
					}
				}
			});
			return convertView;
		}
	}

	class ViewHolder {
		private TextView tv;
		private ImageButton btn;
	}
	
}
/*
 * private boolean isConnect(Context context) { ConnectivityManager conManager =
 * (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 * 
 * NetworkInfo networkInfo = conManager.getActiveNetworkInfo(); if (networkInfo
 * != null) { // 注意，这个判断一定要的哦，要不然会出错 return networkInfo.isAvailable(); } return
 * false; }
 */

/*
 * if (isConnect(this) == false) { new AlertDialog.Builder(this)
 * .setTitle("网络错误") .setMessage("网络连接失败，请确认网络连接") .setPositiveButton("确定", new
 * DialogInterface.OnClickListener() {
 * 
 * @Override public void onClick(DialogInterface arg0, int arg1) { // TODO
 * Auto-generated method stub Intent intent = new Intent(
 * "android.settings.WIRELESS_SETTINGS"); startActivity(intent); } }).show(); }
 */